package com.zeus.core.log.config;

import com.zeus.common.log.ZeusLoggerConfig;
import com.zeus.core.log.appender.Log4jMonitorAppender;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Enumeration;

/**
 * Log4j配置信息
 *
 * @author f1ybear_wang 2021/6/3  0:18
 */
public class Log4jConfig {
    private final static Logger log = LoggerFactory.getLogger(Log4jConfig.class);

    /**
     * Log4j配置信息初始化
     *
     * @return 是否初始化成功
     * @author f1ybear_wang 2021/6/3 0:17
     */
    public static boolean init() {
        try {
            // 添加Log4jMonitorAppender
            org.apache.log4j.Logger log4jLogger = org.apache.log4j.Logger.getRootLogger();
            if (log4jLogger != null) {
                boolean hasAppender = false;
                Enumeration allAppender = log4jLogger.getAllAppenders();
                while (allAppender.hasMoreElements()) {
                    hasAppender = true;
                    Object obj = allAppender.nextElement();
                    if (obj != null) {
                        // 判断是否已经注入appender
                        if (Log4jMonitorAppender.class.isAssignableFrom(obj.getClass())) {
                            if (log.isInfoEnabled() && ZeusLoggerConfig.needEnableLogger()) {
                                log.info(">>> Zeus日志监控模块, into LogMonitorApplicationListener，log4j日志监控配置已经注入appender");
                            }
                            return true;
                        }
                    }
                }
                if (hasAppender) {
                    log4jLogger.addAppender(new Log4jMonitorAppender());
                    if (log.isInfoEnabled() && ZeusLoggerConfig.needEnableLogger()) {
                        log.info(">>> Zeus日志监控模块, into LogMonitorApplicationListener, log4j日志监控配置信息初始化完成");
                    }
                    return true;
                }
            }
        } catch (Throwable ignored) {
            // 忽略
        }
        return false;
    }
}
